class Game {
  constructor() {
    // 初始事件
    this.time = 60;
    // 打中地鼠次数
    this.totalNum = 0;
    // 地鼠消失的快慢  毫秒
    this.level = 550;
    // 定时器
    this.timeOut = null;
    // 初始化play 绑定this
    this.play = this.play.bind(this);
  }
  getById(id) {
    return document.getElementById(id);
  }
  // 开始游戏
  play() {
    // 开始游戏
    // 1、时间减少
    // 2、地鼠随机出现
    // 3、过一段时间地数消失
	console.log(this.level)
    clearInterval(this.timeOut);
    this.timeOut = setInterval(() => {
      this.time--;
      if (this.time == 0) {
        // 游戏结束了
        this.end();
      }
      this.getById("time").innerText = this.time;
      // 让地鼠随机出现 隔段时间消失
      this.getRadom();
    }, 1000);
  }
  // 游戏重点
  getRadom = () => {
    // 洞的总数
    let nums = this.getById("mouseFrame").children.length;
    // 取0-nums之间的随机数
    let randomNum = parseInt(Math.random() * nums);
    // console.log(randomNum);
    let curMouse = this.getById("mouseFrame").children[randomNum];
    curMouse.className = "mouse out";
    setTimeout(() => {
      curMouse.className = "mouse";
    }, this.level);
  };
  // 游戏结束
  end = () => {
    clearInterval(this.timeOut);
    // 时间重置
    this.time = this.getById("time").innerText = 60;
    // 打中的次数重置
    this.totalNum = this.getById("hitNum").innerText = 0;
    const select = this.getById("level");
  };
  // 打击地鼠
  hitMouse = () => {
    const mouseFrame = this.getById("mouseFrame");
    // 锤子的动画
    mouseFrame.addEventListener("mousedown", () => {
      const gameBox = this.getById("gameBox");
      // console.log(gameBox.className);
      gameBox.className =
        gameBox.className === "mouses-box"
          ? "mouses-box mouses-box-down"
          : "mouses-box";
    });
    // 锤子的动画
    mouseFrame.addEventListener("mouseup", () => {
      const gameBox = this.getById("gameBox");
      // console.log(gameBox.className);
      gameBox.className = "mouses-box";
    });
    mouseFrame.addEventListener("click", (e) => {
      // console.log(e);
      // 事件委托
      let target = e.target;
      let className = target.className;
      if (className.indexOf("out") !== -1) {
        target.className = "mouse";
        // 右上角的打中次数加一
        this.getById("hitNum").innerText = ++this.totalNum;
      }
    });
  };

  gameOver = () => {
    this.end();
  };
}

let game = new Game();
game.hitMouse();
start = game.play;
gameOver = game.gameOver;
document.onkeydown = function(event) {
          var e = event || window.event || arguments.callee.caller.arguments[0];
          if (e && e.keyCode == 27) { // 按 Esc  结束游戏
             gameOver()
          }
}

